<template>
  <div class="fa" :style="{ height: faheight }">
    <div class="title-sign">样本出库</div>
    <a-form ref="userform" :model="formdata" name="basic" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }"
      autocomplete="off">
      <a-row style="height: 45px">
        <a-col :span="6">
          <a-form-item label="出库单号" name="id">
            <a-input v-model:value="formdata.id" :disabled="true" />
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="归还日期">
            <a-date-picker :disabled="!selectSamples" v-model:value="formdata.time" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div v-if="selectSamples">
      <div class="title-sign">选择样本</div>
      <a-form ref="userform" :model="formdata" name="basic" :wrapper-col="{ span: 20 }" autocomplete="off">
        <a-row style="height: 40px">
          <a-col :span="1" style="text-align: center; height: 32px; line-height: 32px"> 查询条件 </a-col>
          <a-col :span="3">
            <a-form-item>
              <a-select allowClear v-model:value="searchdata.projectId" placeholder="课题组">
                <a-select-option v-for="j in antSelect" :value="j.id" :key="j.id">{{ j.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item>
              <a-input v-model:value="searchdata.originalSerial" placeholder="样本编号" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item>
              <a-input v-model:value="searchdata.name" placeholder="样本名称" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item>
              <a-input v-model:value="searchdata.extDataList[0].value" placeholder="样本类型" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-form-item>
              <a-input v-model:value="searchdata.serial" placeholder="数字编号" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-button type="primary" style="margin-left: 10px; height: 30px" @click="getSearchData()">查询</a-button>
          </a-col>
        </a-row>
      </a-form>
      <vxe-table align="center" :row-config="{ height: 40 }" show-overflow ref="xTable1" :border="false" auto-resize
        :data="demo1.tableData" max-height="300px" @toggle-row-expand="toggleExpandChangeEvent">
        <vxe-column type="expand" width="80" :fixed="demo1.expandFixed">
          <template #content="{ row, rowIndex }">
            <div class="expand-wrapper">
              <vxe-table max-height="350" ref="tableson" align="center" size="mini" border
                :data="demo1.boxData?.subSpecimens" show-overflow auto-resize @checkbox-all="selectAllChangeEvent1"
                @checkbox-change="selectChangeEvent1">
                <vxe-column type="checkbox" width="60"></vxe-column>
                <vxe-column field="seat" title="位置"></vxe-column>
                <vxe-column field="originalSerial" title="样本编号"></vxe-column>
                <vxe-column field="name" title="样本名称"></vxe-column>
                <vxe-column field="specimen_type" title="样本类型"></vxe-column>
                <vxe-column field="sampleTime" title="采样日期"></vxe-column>
                <vxe-column field="serial" title="数字编号"></vxe-column>
                <vxe-column field="newcapacity" title="容量"></vxe-column>
              </vxe-table>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="serial" title="冻存盒编号"></vxe-column>
        <vxe-column field="boxType" title="冻存盒类型"></vxe-column>
        <vxe-column field="storageDesp" title="储存位置"></vxe-column>
      </vxe-table>
    </div>
    <div class="title-sign" style="margin-top: 10px">已选样本</div>
    <div style="margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center">
      <span>已选择样本数量 {{ outList.allNum }} 支</span>
      <div>
        <a-button type="primary" @click="getOut" :disabled="!selectSamples && step >= 2">取出样本</a-button>
        <a-button type="primary" style="margin: 0 15px" :disabled="step != 2" @click="artificial">手动核查</a-button>
        <a-button type="primary" @click="NumberEquipment('BOX')" :disabled="step != 2">自动核查</a-button>
      </div>
    </div>
    <vxe-table align="center" :row-config="{ height: 40, isHover: true }" show-overflow ref="xTable2" :border="false"
      auto-resize :data="outList.tableData" :max-height="selectSamples ? '250px' : '800px'"
      @toggle-row-expand="toggleExpandChangeEvent2">
      <vxe-column type="expand" width="80" :fixed="demo1.expandFixed">
        <template #content="{ row, rowIndex }">
          <div class="expand-wrapper">
            <vxe-table ref="vxetable10" align="center" size="mini" border
              :data="row.newSpecimens ? row.newSpecimens : row.subSpecimens">
              <vxe-column field="seat" title="位置"></vxe-column>
              <vxe-column field="originalSerial" title="样本编号"></vxe-column>
              <vxe-column field="name" title="样本名称"></vxe-column>
              <vxe-column field="specimen_type" title="样本类型"></vxe-column>
              <vxe-column field="sampleTime" title="采样日期"></vxe-column>
              <vxe-column field="serial" title="数字编号"></vxe-column>
              <vxe-column field="newcapacity" title="容量"></vxe-column>
              <vxe-column field="status" title="取出" width="70px" style="text-align: center" v-if="!selectSamples">
                <template #default="{ row }">
                  <svg v-if="step >= 2" t="1680592527152" class="icon" viewBox="0 0 1024 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="2909" width="45" height="20">
                    <path
                      d="M512.024381 0C229.205333 0 0 229.205333 0 512.024381 0 794.770286 229.205333 1024 512.024381 1024 794.770286 1024 1024 794.770286 1024 512.024381 1024 229.205333 794.770286 0 512.024381 0M849.603048 353.328762l-385.462857 385.462857c-9.411048 9.411048-21.723429 14.09219-34.06019 14.09219s-24.697905-4.681143-34.084571-14.09219l-221.622857-221.647238c-18.822095-18.822095-18.822095-49.322667 0-68.120381 18.822095-18.846476 49.322667-18.846476 68.144762 0l187.562667 187.562667 351.378286-351.402667c18.822095-18.822095 49.322667-18.822095 68.144762 0C868.425143 304.006095 868.425143 334.506667 849.603048 353.328762"
                      fill="#5bdc9c" p-id="2910" data-spm-anchor-id="a313x.7781069.0.i0" class=""></path>
                  </svg>
                  <svg v-else t="1680592590083" class="icon" viewBox="0 0 1024 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="3923" width="45" height="20">
                    <path
                      d="M512 981.333333C252.8 981.333333 42.666667 771.2 42.666667 512S252.8 42.666667 512 42.666667s469.333333 210.133333 469.333333 469.333333-210.133333 469.333333-469.333333 469.333333z m44.245333-469.333333l159.914667-159.914667a31.274667 31.274667 0 1 0-44.245333-44.245333L512 467.754667 352.085333 307.84a31.274667 31.274667 0 1 0-44.245333 44.245333L467.754667 512l-159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333 44.245333L512 556.245333l159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333-44.245333L556.245333 512z"
                      fill="#F5222D" p-id="3924"></path>
                  </svg>
                </template>
              </vxe-column>
              <vxe-column field="status" title="核查" width="70px" style="text-align: center" v-if="!selectSamples">
                <template #default="{ row }">
                  <svg v-if="step >= 3 || row.checkStatus >= 3" t="1680592527152" class="icon" viewBox="0 0 1024 1024"
                    version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2909" width="45" height="20">
                    <path
                      d="M512.024381 0C229.205333 0 0 229.205333 0 512.024381 0 794.770286 229.205333 1024 512.024381 1024 794.770286 1024 1024 794.770286 1024 512.024381 1024 229.205333 794.770286 0 512.024381 0M849.603048 353.328762l-385.462857 385.462857c-9.411048 9.411048-21.723429 14.09219-34.06019 14.09219s-24.697905-4.681143-34.084571-14.09219l-221.622857-221.647238c-18.822095-18.822095-18.822095-49.322667 0-68.120381 18.822095-18.846476 49.322667-18.846476 68.144762 0l187.562667 187.562667 351.378286-351.402667c18.822095-18.822095 49.322667-18.822095 68.144762 0C868.425143 304.006095 868.425143 334.506667 849.603048 353.328762"
                      fill="#5bdc9c" p-id="2910" data-spm-anchor-id="a313x.7781069.0.i0" class=""></path>
                  </svg>
                  <svg v-else t="1680592590083" class="icon" viewBox="0 0 1024 1024" version="1.1"
                    xmlns="http://www.w3.org/2000/svg" p-id="3923" width="45" height="20">
                    <path
                      d="M512 981.333333C252.8 981.333333 42.666667 771.2 42.666667 512S252.8 42.666667 512 42.666667s469.333333 210.133333 469.333333 469.333333-210.133333 469.333333-469.333333 469.333333z m44.245333-469.333333l159.914667-159.914667a31.274667 31.274667 0 1 0-44.245333-44.245333L512 467.754667 352.085333 307.84a31.274667 31.274667 0 1 0-44.245333 44.245333L467.754667 512l-159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333 44.245333L512 556.245333l159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333-44.245333L556.245333 512z"
                      fill="#F5222D" p-id="3924"></path>
                  </svg>
                </template>
              </vxe-column>
              <vxe-column title="操作" v-else>
                <template #default="{ row }">
                  <vxe-button status="primary" size="mini" :disabled="!selectSamples"
                    @click="deleteSample(row, false)">移除</vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="serial" title="冻存盒编号"></vxe-column>
      <vxe-column field="boxType" title="冻存盒类型"></vxe-column>
      <vxe-column field="storageDesp" title="储存位置"></vxe-column>
      <vxe-column field="status" title="取出" width="70px" style="text-align: center" v-if="!selectSamples">
        <template #default="{ row }">
          <svg v-if="step >= 2" t="1680592527152" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="2909" width="45" height="20">
            <path
              d="M512.024381 0C229.205333 0 0 229.205333 0 512.024381 0 794.770286 229.205333 1024 512.024381 1024 794.770286 1024 1024 794.770286 1024 512.024381 1024 229.205333 794.770286 0 512.024381 0M849.603048 353.328762l-385.462857 385.462857c-9.411048 9.411048-21.723429 14.09219-34.06019 14.09219s-24.697905-4.681143-34.084571-14.09219l-221.622857-221.647238c-18.822095-18.822095-18.822095-49.322667 0-68.120381 18.822095-18.846476 49.322667-18.846476 68.144762 0l187.562667 187.562667 351.378286-351.402667c18.822095-18.822095 49.322667-18.822095 68.144762 0C868.425143 304.006095 868.425143 334.506667 849.603048 353.328762"
              fill="#5bdc9c" p-id="2910" data-spm-anchor-id="a313x.7781069.0.i0" class=""></path>
          </svg>
          <svg v-else t="1680592590083" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="3923" width="45" height="20">
            <path
              d="M512 981.333333C252.8 981.333333 42.666667 771.2 42.666667 512S252.8 42.666667 512 42.666667s469.333333 210.133333 469.333333 469.333333-210.133333 469.333333-469.333333 469.333333z m44.245333-469.333333l159.914667-159.914667a31.274667 31.274667 0 1 0-44.245333-44.245333L512 467.754667 352.085333 307.84a31.274667 31.274667 0 1 0-44.245333 44.245333L467.754667 512l-159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333 44.245333L512 556.245333l159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333-44.245333L556.245333 512z"
              fill="#F5222D" p-id="3924"></path>
          </svg>
        </template>
      </vxe-column>
      <vxe-column field="status" title="核查" width="70px" style="text-align: center" v-if="!selectSamples">
        <template #default="{ row }">
          <svg v-if="step >= 3 || row.checkStatus >= 3" t="1680592527152" class="icon" viewBox="0 0 1024 1024"
            version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2909" width="45" height="20">
            <path
              d="M512.024381 0C229.205333 0 0 229.205333 0 512.024381 0 794.770286 229.205333 1024 512.024381 1024 794.770286 1024 1024 794.770286 1024 512.024381 1024 229.205333 794.770286 0 512.024381 0M849.603048 353.328762l-385.462857 385.462857c-9.411048 9.411048-21.723429 14.09219-34.06019 14.09219s-24.697905-4.681143-34.084571-14.09219l-221.622857-221.647238c-18.822095-18.822095-18.822095-49.322667 0-68.120381 18.822095-18.846476 49.322667-18.846476 68.144762 0l187.562667 187.562667 351.378286-351.402667c18.822095-18.822095 49.322667-18.822095 68.144762 0C868.425143 304.006095 868.425143 334.506667 849.603048 353.328762"
              fill="#5bdc9c" p-id="2910" data-spm-anchor-id="a313x.7781069.0.i0" class=""></path>
          </svg>
          <svg v-else t="1680592590083" class="icon" viewBox="0 0 1024 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="3923" width="45" height="20">
            <path
              d="M512 981.333333C252.8 981.333333 42.666667 771.2 42.666667 512S252.8 42.666667 512 42.666667s469.333333 210.133333 469.333333 469.333333-210.133333 469.333333-469.333333 469.333333z m44.245333-469.333333l159.914667-159.914667a31.274667 31.274667 0 1 0-44.245333-44.245333L512 467.754667 352.085333 307.84a31.274667 31.274667 0 1 0-44.245333 44.245333L467.754667 512l-159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333 44.245333L512 556.245333l159.914667 159.914667a31.274667 31.274667 0 1 0 44.245333-44.245333L556.245333 512z"
              fill="#F5222D" p-id="3924"></path>
          </svg>
        </template>
      </vxe-column>
      <vxe-column title="操作" v-else>
        <template #default="{ row }">
          <vxe-button status="primary" size="mini" :disabled="!selectSamples"
            @click="deleteSample(row, true)">移除</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <div style="display: flex; justify-content: center; width: 90%; margin-top: 40px">
      <a-button type="primary" style="margin-right: 10px" @click="renovate"
        :disabled="!selectSamples && step >= 2">重置</a-button>
      <a-button type="primary" :disabled="step != 3" @click="openHeight">确认出库</a-button>
    </div>
  </div>
  <doubleLock @submitData="okgetOut" :id="formdata.id" :tableData="outList.tableData" ref="double"></doubleLock>
  <Modal :destroyOnClose="true" :maskClosable="false" :footer="null" title="底单存档" width="60%"
    v-model:visible="showHighCamera">
    <HighCameracopy @uploadSuccess="uploadSuccess" :processCfg="processCfg" :routerRecord="true"
      highCameraId="inputManageHighCamera" canvasCameraId="inputManageCanvasCamera" :billId="outid" :billType="3">
    </HighCameracopy>
  </Modal>
  <!-- //出库等待提示框 -->
  <a-drawer title="出库状态" width="80%" :visible="visibleloading" @close="onClose">
    <p>出库单号 : {{ formdata.id }}</p>
    <div style="width: 80%; height: 90%">
      <vxe-table border="default" ref="vxeTable123" :data="promptData" max-height="80%" :row-config="{ height: 35 }"
        show-overflow>
        <vxe-column field="boxNo" title="冻存盒编号"></vxe-column>
        <vxe-column field="specimenCount" title="出库数量"></vxe-column>
        <vxe-column field="storageName" title="出库设备" width="170px"></vxe-column>
        <vxe-column field="sampleAddress" title="操作">
          <template #default="{ row }">
            <span v-if="row.deviceId == 0">出库完毕</span>
            <span v-else>
              <span v-if="row.status == 0" style="color: skyblue">设备正在执行自动取出，请等待…</span>
              <span v-else-if="row.status == 1">取出完毕</span>
              <span v-else style="color: red">取出失败</span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div style="display: flex; justify-content: center; align-items: center">
      <a-button type="primary" style="margin-right: 10px" @click="onClose">关闭</a-button>
      <a-button type="primary" @click="onClose" :disabled="nextStep">下一步</a-button>
    </div>
    <Modal :destroyOnClose="true" title="失败" :maskClosable="false" width="30%" :footer="null"
      v-model:visible="failvisible">
      <p style="text-align: center; font-size: 16px; margin-bottom: 10px">样本入库失败,请选择下一步操作:</p>
      <div style="width: 100%; display: flex; justify-content: center; align-items: center; margin-bottom: 10px">
        <a-button type="primary" style="margin-right: 20px" @click="retry(true)">重试</a-button>
        <a-button type="primary" @click="retry(false)">忽略</a-button>
      </div>
    </Modal>
    <Modal :destroyOnClose="true" title="提示" :maskClosable="false" width="30%" :footer="null" @cancel="confirmRemoval"
      v-model:visible="promptInfo">
      <p style="text-align: center; font-size: 16px; margin-bottom: 10px">请将样本从指定位置取出</p>
      <div style="width: 100%; display: flex; justify-content: center; align-items: center; margin-bottom: 10px">
        <a-button type="primary" style="margin-right: 20px" @click="confirmRemoval">确定</a-button>
      </div>
    </Modal>
  </a-drawer>
</template>
<script setup lang="tsx">
import doubleLock from './components/doubleLock.vue';
import { reactive, ref, nextTick, onBeforeUnmount } from 'vue';
import { subscript, padData, addSpecimenType } from '@/libs/utils';
import { message, Modal } from 'ant-design-vue';
import { getOutputData, generateBatchNo, postOutPut, billOut, patchOutPut, getIssueData, billOutTakeout, billOutIgnore } from '../../api/out_input';
import { getBasicPointList } from '../../api/input_manage';
import { searchDevice, deviceQuery } from '@/api/emq-openapi';
import { taskSearch } from '@/api/base/task-data';
import { useRoute, useRouter } from 'vue-router';
import MQTT from '@/framework/utils/mqtt';
import HighCameracopy from '@/components/photograph/HighCameracopy.vue';
import { userSearch } from '@/api/operationFlow';
import dayjs from 'dayjs';
import { postCheck } from '@/api/utils';
const outid = ref(null); //出库单id
//1新建、2已经全部取出、3已经全部核查、4附件上传完毕、 8关闭、9出库已完成。最终提交时该字段应该为9
const step = ref(0);
const route = useRoute();
const router = useRouter();
const showHighCamera = ref(false);
const visibleloading = ref(false);
const promptInfo = ref(false);
const vxeTable123 = ref();
const promptData = ref([]);
const onClose = () => {
  visibleloading.value = false;
  clearInterval(timer.value);
  timer.value = null;
};
const nextStep = ref(true);
const failvisible = ref(false);
const timer: any = ref(null);
const confirmRemoval = () => {
  promptInfo.value = false
  MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
}
// 基点任务失败重试和忽略
const retry = async (bol) => {
  if (bol) {
    billOutTakeout(outid.value).then((res) => {
      failvisible.value = false;
      websort();
    });
  } else {
    let i = outList.tableData.findIndex((el) => el.serial == promptData.value.find((item) => item.status == 2)?.boxNo);
    let arr = promptData.value.filter(item => item.status == 2).map(el => el.boxNo)
    let newArr = []
    outList.tableData.forEach(item => { if (arr.includes(item.serial)) newArr.push(item) })
    let { result } = await billOutIgnore(outid.value, { links: newArr, batchNo: formdata.id });
    if (result.status == 8) {
      message.warning('单据无绑定盒信息')
      router.push({ name: 'out_record' })
    }
    for (let i = 0; i < outList.tableData.length; i++) {
      if (arr.includes(outList.tableData[i].serial)) {
        outList.tableData.splice(i, 1);
        i--
      }
    }

    if (!(outList.tableData.length == 0)) {
      failvisible.value = false;
      websort();
    } else {
      failvisible.value = false;
      onClose();
      outList.tableData = [];
    }
  }
};
//每5s刷新数据
const websort = async () => {
  seejidian();
  timer.value ? clearInterval(timer.value) : '';
  timer.value = setInterval(async () => {
    seejidian();
  }, 5000);
};
//打开高拍仪
const openHeight = () => {
  showHighCamera.value = true;
};
const uploadSuccess = () => {
  showHighCamera.value = false;
};
// 查看是否有基点任务
const seejidian = async () => {
  try {
    const { result } = await getBasicPointList({ billId: outid.value, billType: 2 });
    promptData.value = result.dataList;
    if (result.dataList.some((item) => item.status == 2)) {
      failvisible.value = true;
      clearInterval(timer.value);
    }
    if (result.dataList.every((item) => item.status == 1)) {
      nextStep.value = false;
      getOut2(4);
      clearInterval(timer.value);
    }
  } catch (error) {
    console.log(error);
  }

};
//权限管理
const processCfg = reactive({
  isArchive: true, //是否开启底单存档文件上传
  isCapture: true, //是否开启高拍仪
  isSignature: true, //是否开启电子签名
});
const EchoInput = async (id) => {
  const { result } = await billOut(id);
  formdata.time = dayjs(result.cautionTime, 'YYYY-MM-DD')
  let specimenOutableVoList = [];
  result.links.forEach((item) => {
    specimenOutableVoList.push(...item.subSpecimens);
    addSpecimenType(item.subSpecimens);
    item.subSpecimens.forEach((el) => {
      el.seat = subscript(el.sortIndex, item.boxRows);
    });
  });
  const res = await userSearch({ type: 3, specimenOutableVoList });
  processCfg.isArchive = res.result.processCfg.isArchive;
  processCfg.isCapture = res.result.processCfg.isCapture;
  processCfg.isSignature = res.result.processCfg.isSignature;
  formdata.id = result.batchNo;
  outid.value = result.id;
  if (result?.billStatus == 0 || result?.billStatus == 2) {
    visibleloading.value = true;
    websort();
  }

  selectSamples.value = result.status == 0;
  step.value = result.status;
  outList.tableData = result.links;
  if (result.status == 2) {
    outList.tableData.forEach((item) => {
      item.checkStatus = result.status;
      item.subSpecimens.forEach((el) => {
        el.checkStatus = result.status;
      });
    });
  }
};
if (route.query.id) {
  // 获取数据回显
  EchoInput(route.query.id);
}


const antSelect = ref([]);
const formdata = reactive({
  id: '',
  system: '',
  type: '',
  name: '',
  manage: '',
  time: '',
});
const searchdata = reactive({
  projectId: null,
  originalSerial: '',
  name: '',
  extDataList: [
    {
      name: 'specimen_type',
      value: '',
    },
  ],
  categoryName: '',
  serial: '',
});
const selectSamples = ref(true);
const double = ref();
const demo1 = reactive({
  seqFixed: null,
  expandFixed: null,
  ageFixed: null,
  tableData: [],
  boxData: {},
});
const xTable1 = ref();
const xTable2 = ref();
const tableson = ref();
const vxetable10 = ref();
const storerow = ref(100000);
const outList: any = reactive({
  seqFixed: null,
  expandFixed: null,
  ageFixed: null,
  tableData: [],
  allNum: 0,
});
//获取出库单号
if (!route.query.id) {
  const getOutNo = (async () => {
    const { result } = await generateBatchNo();
    formdata.id = result;
  })();
}
const taskxiangmuz = (async () => {
  let queryOpt = {
    pageNum: 1, // 当前页数
    pageSize: 1000, // 页面大小
    'orderBy[0].field': 'createTime', // 默认排序字段
    'orderBy[0].order': 'desc', // 默认排序方式
  };
  let { result } = await taskSearch(queryOpt);
  antSelect.value = result.data;
})();
const faheight = ref(window.innerHeight + 'px');
const toggleExpandChangeEvent = ({ expanded, row, rowIndex }) => {
  if (expanded) {
    demo1.boxData = row;
    storerow.value == rowIndex ? '' : xTable1.value.setRowExpand(demo1.tableData[storerow.value], false);
    storerow.value = rowIndex;
    nextTick(() => {
      let obj = outList.tableData.find((item) => item.epcId == demo1.boxData.epcId);
      if (!(obj?.newSpecimens && obj.newSpecimens.length > 0)) {
        obj.newSpecimens = [];
        obj.subSpecimens.forEach((element) => {
          obj.newSpecimens.push(demo1.boxData.subSpecimens[demo1.boxData.subSpecimens.findIndex((item) => item.id == element.id)]);
        });
      }
      obj ? tableson.value.setCheckboxRow(obj.newSpecimens, true) : '';
    });
  }
  getSelection();
};
const toggleExpandChangeEvent2 = ({ expanded }) => {
  console.log(expanded);
};
const getSearchData = async () => {
  let queryOpt = {
    pageNum: 1,
    pageSize: 1000,
    'orderBy[0].field': 'id',
    'orderBy[0].order': 'asc',
    queryExtData: true,
  };
  const { result } = await getOutputData(searchdata, queryOpt);
  demo1.tableData = result.data.filter((item) => item.subSpecimens && item.subSpecimens.length > 0);
  demo1.tableData.forEach((item) => {
    addSpecimenType(item.subSpecimens);
    item.subSpecimens.forEach((el) => {
      el.seat = subscript(el.sortIndex, item.boxRows);
    });
  });
  if (route.query.strainIds) {
    let { result } = await getIssueData(route.query.strainIds);
    result.forEach(item => {
      let obj: any = demo1.tableData.find(ul => ul.epcId == item.epcId)
      if (obj) {
        item.subSpecimens.forEach((el, index) => {
          obj.subSpecimens.forEach(va => {
            if (va.id == el.id) {
              item.subSpecimens[index] = va
            }
          })
        })
      }

    })
    outList.tableData = result;
  }

};
getSearchData();
const renovate = () => {
  Modal.confirm({
    title: '确定重置入库单吗?',
    onOk() { },
  });
};
//移除
const deleteSample = (row, bol) => {
  if (bol) {
    outList.tableData.splice(
      outList.tableData.findIndex((item) => item.epcId == row.epcId),
      1,
    );
    xTable2.value.loadData(outList.tableData);
    if (row.epcId == demo1.boxData.epcId) {
      tableson.value.clearCheckboxRow();
    }
  } else {
    let obj = outList.tableData.find((item) => item.epcId == row.epcId);
    obj.newSpecimens.splice(
      obj.newSpecimens.findIndex((item) => item.id == row.id),
      1,
    );
    vxetable10.value.loadData(obj.newSpecimens);
    if (obj.epcId == demo1.boxData.epcId) {
      tableson.value.clearCheckboxRow();
      tableson.value.setCheckboxRow(obj.newSpecimens, true);
    }
    if (obj.newSpecimens.length == 0) {
      outList.tableData.splice(
        outList.tableData.findIndex((item) => item.epcId == obj.epcId),
        1,
      );
      xTable2.value.loadData(outList.tableData);
    }
  }
  getSelection();
};
// 获取当前选择的样本数量
const getSelection = () => {
  outList.allNum = 0;
  outList.tableData.forEach((item) => {
    outList.allNum += item.newSpecimens.length;
  });
};
const selectChangeEvent1 = ({ checked, row, rowIndex }) => {
  let obj = outList.tableData.find((item) => item.epcId == demo1.boxData.epcId);
  if (obj) {
    if (checked) {
      obj.newSpecimens.push(row);
      vxetable10.value.reloadData(obj.newSpecimens);
    } else {
      obj.newSpecimens.splice(
        obj.newSpecimens.findIndex((item) => item.id == row.id),
        1,
      );
      if (obj.newSpecimens.length == 0) {
        outList.tableData.splice(
          outList.tableData.findIndex((item) => item.epcId == demo1.boxData.epcId),
          1,
        );
        xTable2.value.reloadData(outList.tableData);
      }
      vxetable10.value.reloadData(obj.newSpecimens);
    }
  } else {
    outList.tableData.push(demo1.boxData);
    outList.tableData[outList.tableData.length - 1].newSpecimens = [];
    outList.tableData[outList.tableData.length - 1].newSpecimens.push(row);
    xTable2.value.reloadData(outList.tableData);
  }
  getSelection();
};
const selectAllChangeEvent1 = ({ checked }) => {
  if (checked) {
    const records = tableson.value.getCheckboxRecords();
    outList.tableData.push(demo1.boxData);
    outList.tableData[outList.tableData.length - 1].newSpecimens = [];
    outList.tableData[outList.tableData.length - 1].newSpecimens = records;
  } else {
    outList.tableData.splice(
      outList.tableData.findIndex((item) => item.epcId == demo1.boxData.epcId),
      1,
    );
  }
  xTable2.value.loadData(outList.tableData);
  getSelection();
};
//取出样本
const getOut = async () => {
  if (!(outList.tableData[0]?.subSpecimens?.length > 0)) return message.warning('请选择数据');
  if (selectSamples.value) {
    outList.tableData.forEach((item) => {
      if (item.newSpecimens) {
        item.subSpecimens = item.newSpecimens;
      } else {
        item.newSpecimens = item.subSpecimens
      }
    });
    let data = {
      batchNo: formdata.id,
      status: 0,
      systemId: 0,
      links: outList.tableData,
      cautionTime: formdata.time,
    };
    let specimenOutableVoList = [];

    outList.tableData.forEach((item) => specimenOutableVoList.push(...item.subSpecimens));

    const { result } = await postOutPut(data);
    const res = await userSearch({ type: 3, specimenOutableVoList });
    processCfg.isArchive = res.result.processCfg.isArchive;
    processCfg.isCapture = res.result.processCfg.isCapture;
    processCfg.isSignature = res.result.processCfg.isSignature;
    outid.value = result;
    selectSamples.value = false;
    outList.tableData.forEach((item) => {
      item.subSpecimens = item.newSpecimens;
    });
  }
  double.value.onOpen();
};
const operatorName = ref()
// 确认取出样本
const okgetOut = async (str) => {
  operatorName.value = str
  getOut2(3);
};
const getOut2 = async (num) => {
  //num==3表示是取出状态,还未核查给使有的盒子和冻存管上个状态checkStatus=2
  if (num >= 3) {
    outList.tableData.forEach((item) => {
      item.submitStatus = num;
      item.checkStatus = 2;
      item.subSpecimens.forEach((el) => {
        el.status = 1;
        el.checkStatus = 2;
      });
    });
  } else {
    outList.tableData.forEach((item) => {
      item.submitStatus = num;
      item.subSpecimens.forEach((el) => {
        el.status = 1;
      });
    });
  }
  let data = {
    batchNo: formdata.id,
    status: 0,
    systemId: 0,
    id: outid.value,
    links: outList.tableData,
    operatorName: operatorName.value,
    userName: '11',
  };
  if (num == 4) {
    data.status = 2;
  }
  const { result } = await patchOutPut(data);
  if (num == 3) {
    padData(outList.tableData, formdata.id, 'OUT');
    promptInfo.value = true
  }
  step.value = result;
  MQTT.publish('bims/box/' + check.boxsn + '/check', '{"on":false}');
  if (result == 1) {
    visibleloading.value = true;
    websort();
  }
  if (result == 2) {
    EchoInput(outid.value);
  }
};

//手动核查
const artificial = () => {
  outList.tableData.forEach((el) => {
    el.checkStatus = 3;
    el.subSpecimens.forEach((ul) => {
      ul.checkStatus = 3;
    });
  });
  getOut2(2);
};
// 单据数据
const check: any = reactive({
  equipmentSow: [],
  subSpecimens: [],
  check: '',
  id: '',
  boxsn: '',
});
//自动核查
const NumberEquipment = async (type) => {
  let { data } = await searchDevice([]);
  let devices = data.filter((item) => item.connected && item.clientid && item.clientid.startsWith(type));
  if (devices.length === 0) {
    check.equipmentSow = [];
    // return message.warning('未检测到交接仓')
  } else if (devices.length === 1) {
    check.equipmentSow = [{ sn: devices[0].clientid.split('_')[1] }];
  } else {
    let paging = {
      pageNum: 1,
      pageSize: 999999,
      'orderBy[0].field': 'createTime',
      'orderBy[0].order': 'desc',
    };
    let res = await deviceQuery(paging);
    devices.forEach((el) => {
      let str = el.clientid.split('_')[1];
      res.data.result.data.forEach((ul) => {
        if (ul.sn == str) check.equipmentSow.push({ name: ul.name, sn: str });
      });
    });
  }
  check.subSpecimens = outList.tableData
    .filter((item) => item.checkStatus == 2)
    .map((item, i) => ({
      num: i + 1,
      epc: item.epc,
      submitStatus: item.submitStatus === 2 ? '已核查' : '未核查',
      originalSerial: item.originalSerial,
      name: item.name,
      serial: item.serial,
    }));
  let arr: any = [];
  outList.tableData.forEach((el) => {
    el.subSpecimens.forEach((item, i) => {
      arr.push({
        num: i + 1,
        epc: item.epc,
        submitStatus: item.submitStatus === 2 ? '已核查' : '未核查',
        originalSerial: item.originalSerial,
        name: item.name,
        serial: item.serial,
      });
    });
  });
  let taskInfo = {
    on: true,
    taskList: { taskType: 'OUT', taskinfo: formdata.id, taskDetail: arr },
  };
  message.success('开始核查');
  check.boxsn = check.equipmentSow[0].sn;
  MQTT.publish('bims/box/' + `${check.equipmentSow[0].sn}` + '/check', JSON.stringify(taskInfo));
  MQTT.subscribe('bims/box/' + `${check.equipmentSow[0].sn}` + '/check/tagReport', 0);
  MQTT.$on('mqtt-msg', (res) => {
    if (router.currentRoute.value.name == 'out_manage_detail' || router.currentRoute.value.name == 'out_manage') {
      let obj = JSON.parse(res.msg.toString());
      obj.tags.forEach((item) => {
        outList.tableData.forEach((el) => {
          el.subSpecimens.forEach((ul) => {
            if (ul.epc == item.epc) {
              ul.checkStatus = 3;
              detection(el);
            }
          });
        });
      });
    }
  });
};
//核查完判断子集是否全部核查完毕
const detection = (data) => {
  if (data.subSpecimens.every((el) => el.checkStatus == 3)) {
    data.checkStatus = 3;
    if (outList.tableData.every((el) => el.checkStatus == 3)) {
      let arr: any = []
      outList.tableData.forEach(item => {
        arr.push(...item.subSpecimens)
      })
      const postdata = { "name": check.boxsn, "deviceType": 41, "useType": 3, "count": arr.length + '支', "parentId": outid.value }
      postCheck(postdata)
      getOut2(2);
    }
  }
};
onBeforeUnmount(() => {
  MQTT.publish('bims/pad/share/taskpush', '{"on":false}');
  MQTT.publish('bims/box/' + check.boxsn + '/check', '{"on":false}');
  MQTT.unsubscribe("bims/box/" + check.boxsn + "/check/tagReport");
});
</script>
<style lang="less" scoped>
.fa {
  width: 100%;
  height: 100%;
  background-color: #fff;
  position: relative;
  padding: 10px;
  overflow: auto;
}

::v-deep .vxe-icon--arrow-right:before {
  border-top-color: #606266;
  border-right-color: #606266
}
</style>
